#include "RenzoVertexBuffer.h"
#include "RenzoTexture.h"

namespace Renzo
{
VertexBuffer::VertexBuffer(void)
: nbTriangles(0)
{
}

VertexBuffer::~VertexBuffer(void)
{
}

void VertexBuffer::add(Vertex* v) {
	vertices.push_back(*v);

	// touch the state
	state = TOUCHED;
}

void VertexBuffer::add(Face* f) {
	Index offset = objectOffsets.back().vertexOffset.start; // vertex offset, not index offset because index value counts on the number of vertices.
	/*
	indices.push_back(f->indices[0] + offset);
	indices.push_back(f->indices[1] + offset);
	indices.push_back(f->indices[2] + offset);
	*/
	indices.push_back(f->indices[0]);
	indices.push_back(f->indices[1]);
	indices.push_back(f->indices[2]);
	++nbTriangles;

	state = TOUCHED;
}

void VertexBuffer::add(Mesh* m) {
	// TODO: must call m->copyToHardware(matTransform). 
	// Don't have matTransform. Cannot use this function. 
	// And, if have matTransform, the vertex must be saved to a buffer for block copying.
}

void VertexBuffer::add(int unit, Texture* t) {
	// TODO: support more than 1 texture unit
	TextureList::iterator i;
	/*
	for (i = textures.begin(); i != textures.end(); i++) {
		if (*i == t) return;
	}*/

	textures.push_back(t); 
	//ObjectOffset& off = objectOffsets.back();
	//off.textureOffset[0].start = vertices.size() - 1; // effective from current vertex	
}

/*
void VertexBuffer::appendObject() {
	ObjectOffset off;
	off.vertexOffset = vertices.size();
	off.indexOffset = indices.size();
	objectOffsets.push_back(off);
}*/

void VertexBuffer::beginObject() {
	ObjectOffset off;
	off.vertexOffset.start = vertices.size();
	off.indexOffset.start = indices.size();
	objectOffsets.push_back(off);
}

void VertexBuffer::endObject() {
	ObjectOffset& off = objectOffsets.back();
	off.vertexOffset.end = vertices.size() - 1;
	off.indexOffset.end = indices.size() - 1;
}

void VertexBuffer::beginTexture() {
	ObjectOffset& off = objectOffsets.back();
	off.textureOffset.start = textures.size();
}

void VertexBuffer::endTexture() {
	ObjectOffset& off = objectOffsets.back();
	off.textureOffset.end = textures.size() - 1;
}


void VertexBuffer::clear() {
	vertices.clear();
	indices.clear();
	textures.clear();
	objectOffsets.clear();
	nbTriangles = 0;
}
}
